package com.fary.context.annotation;

import com.fary.beans.factory.BeanClassLoaderAware;
import com.fary.beans.factory.config.BeanDefinition;
import com.fary.beans.factory.config.BeanDefinitionHolder;
import com.fary.beans.factory.config.ConfigurableListableBeanFactory;
import com.fary.beans.factory.config.SingletonBeanRegistry;
import com.fary.beans.factory.parsing.FailFastProblemReporter;
import com.fary.beans.factory.parsing.PassThroughSourceExtractor;
import com.fary.beans.factory.parsing.ProblemReporter;
import com.fary.beans.factory.parsing.SourceExtractor;
import com.fary.beans.factory.support.BeanDefinitionRegistry;
import com.fary.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import com.fary.beans.factory.support.BeanNameGenerator;
import com.fary.context.EnvironmentAware;
import com.fary.context.ResourceLoaderAware;
import com.fary.core.PriorityOrdered;
import com.fary.core.SpringException;
import com.fary.core.env.Environment;
import com.fary.core.env.StandardEnvironment;
import com.fary.core.io.DefaultResourceLoader;
import com.fary.core.io.ResourceLoader;
import com.fary.core.type.classreading.CachingMetadataReaderFactory;
import com.fary.core.type.classreading.MetadataReaderFactory;
import com.fary.util.Assert;
import com.fary.util.ClassUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;

import static com.fary.context.annotation.AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR;

public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware {

    private static final String IMPORT_REGISTRY_BEAN_NAME = ConfigurationClassPostProcessor.class.getName() + ".importRegistry";

    private final Log logger = LogFactory.getLog(getClass());

    private SourceExtractor sourceExtractor = new PassThroughSourceExtractor();

    private ProblemReporter problemReporter = new FailFastProblemReporter();

    private Environment environment;

    private ResourceLoader resourceLoader = new DefaultResourceLoader();

    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

    private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();

    private boolean setMetadataReaderFactoryCalled = false;

    private final Set<Integer> registriesPostProcessed = new HashSet<>();

    private final Set<Integer> factoriesPostProcessed = new HashSet<>();

    private ConfigurationClassBeanDefinitionReader reader;

    private boolean localBeanNameGeneratorSet = false;

    /* Using short class names as default bean names */
    private BeanNameGenerator componentScanBeanNameGenerator = new AnnotationBeanNameGenerator();

    private BeanNameGenerator importBeanNameGenerator = new AnnotationBeanNameGenerator() {
        @Override
        protected String buildDefaultBeanName(BeanDefinition definition) {
            String beanClassName = definition.getBeanClassName();
            Assert.state(beanClassName != null, "No bean class name set");
            return beanClassName;
        }
    };

    @Override
    public void setBeanClassLoader(ClassLoader beanClassLoader) {
        this.beanClassLoader = beanClassLoader;
        if (!this.setMetadataReaderFactoryCalled) {
            this.metadataReaderFactory = new CachingMetadataReaderFactory(beanClassLoader);
        }
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws SpringException {
        // 判断是否被调用过，返回对象的hashcode
        int registryId = System.identityHashCode(registry);
        if (this.registriesPostProcessed.contains(registryId)) {
            throw new IllegalStateException("postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
        }
        if (this.factoriesPostProcessed.contains(registryId)) {
            throw new IllegalStateException("postProcessBeanFactory already called on this post-processor against " + registry);
        }
        this.registriesPostProcessed.add(registryId);
        processConfigBeanDefinitions(registry);
    }

    public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
        List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
        // 1. 获取已经注册的bean名称
        String[] candidateNames = registry.getBeanDefinitionNames();

        for (String beanName : candidateNames) {
            BeanDefinition beanDef = registry.getBeanDefinition(beanName);
            // 1.1. 如果BeanDefinition 中的configurationClass 属性为full 或者lite ,则意味着已经处理过了,直接跳过
            if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) || ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
                }
            } else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
                // 1.2. 判断对应bean是否为配置类,如果是,则加入到configCandidates
                configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
            }
        }

        // 1.3 如果不存在配置类,则直接return
        if (configCandidates.isEmpty()) {
            return;
        }

        // 2. 对configCandidates 进行 排序,按照@Order 配置的值进行排序
        configCandidates.sort((bd1, bd2) -> {
            int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
            int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
            return Integer.compare(i1, i2);
        });

        // 3. 如果BeanDefinitionRegistry 是SingletonBeanRegistry 子类的话,由于我们当前传入的是DefaultListableBeanFactory,是
        // SingletonBeanRegistry 的子类。因此会将registry强转为SingletonBeanRegistry
        SingletonBeanRegistry sbr = null;
        if (registry instanceof SingletonBeanRegistry) {
            sbr = (SingletonBeanRegistry) registry;
            // setBeanNameGenerator会把localBeanNameGeneratorSet=true（不会考虑internalConfigurationBeanNameGenerator）
            if (!this.localBeanNameGeneratorSet) {
                // 如果localBeanNameGeneratorSet 等于false 并且SingletonBeanRegistry 中有 id 为 org.springframework.context.annotation.internalConfigurationBeanNameGenerator
                // 的bean .则将componentScanBeanNameGenerator,importBeanNameGenerator 赋值为 该bean.
                BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
                if (generator != null) {
                    this.componentScanBeanNameGenerator = generator;
                    this.importBeanNameGenerator = generator;
                }
            }
        }

        if (this.environment == null) {
            this.environment = new StandardEnvironment();
        }

        // 4. 实例化ConfigurationClassParser 为了解析 各个配置类
        ConfigurationClassParser parser = new ConfigurationClassParser(
                this.metadataReaderFactory, this.problemReporter, this.environment,
                this.resourceLoader, this.componentScanBeanNameGenerator, registry);

        // 待被解析的ConfigurationClass集合
        Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
        // 用于保存已经被解析的ConfigurationClass
        Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
        do {
            // 1.解析配置类，这一步只会将加了@Configuration注解以及通过@ComponentScan注解扫描的类才会加入到BeanDefinitionMap中
            // 2.@Import、@Bean解析成ConfigurationClass类
            parser.parse(candidates);
            // 1.校验Configuration类不能被final修饰
            // 2.校验Bean方法，不能被private、static、final修饰
            parser.validate();

            // 获取所有解析出来的Configuration
            Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
            // 删除已经解析过的
            configClasses.removeAll(alreadyParsed);

            // Read the model and create bean definitions based on its content
            if (this.reader == null) {
                this.reader = new ConfigurationClassBeanDefinitionReader(registry, this.sourceExtractor, this.resourceLoader,
                        this.environment, this.importBeanNameGenerator, parser.getImportRegistry());
            }
            // 1.将上一步parser解析出的ConfigurationClass类加载成BeanDefinition
            this.reader.loadBeanDefinitions(configClasses);
            // 记录已经解析的ConfigurationClass
            alreadyParsed.addAll(configClasses);
            // 待被解析的ConfigurationClass集合
            candidates.clear();
            // 判断上面loadBeanDefinitions有没有添加新的BeanDefinition
            if (registry.getBeanDefinitionCount() > candidateNames.length) {
                String[] newCandidateNames = registry.getBeanDefinitionNames();
                Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
                Set<String> alreadyParsedClasses = new HashSet<>();
                for (ConfigurationClass configurationClass : alreadyParsed) {
                    alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
                }
                // 对新添加的BeanDefinition，进行判断是否需要再解析
                for (String candidateName : newCandidateNames) {
                    if (!oldCandidateNames.contains(candidateName)) {
                        BeanDefinition bd = registry.getBeanDefinition(candidateName);
                        // 判断对应bean是否为配置类,如果是,并且没有被解析过，则加入到candidates
                        if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
                                !alreadyParsedClasses.contains(bd.getBeanClassName())) {
                            candidates.add(new BeanDefinitionHolder(bd, candidateName));
                        }
                    }
                }
                candidateNames = newCandidateNames;
            }
        } while (!candidates.isEmpty());

        // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
        if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
            sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
        }

        if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
            // Clear cache in externally provided MetadataReaderFactory; this is a no-op
            // for a shared cache since it'll be cleared by the ApplicationContext.
            ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws SpringException {

    }

    @Override
    public void setEnvironment(Environment environment) {

    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {

    }

    @Override
    public int getOrder() {
        return 0;
    }
}